package malus.shaofeng.com.beiwomusic.activity;

import android.app.Activity;
import android.app.Dialog;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.bitmap.BitmapDisplayConfig;
import com.lidroid.xutils.bitmap.callback.BitmapLoadCallBack;
import com.lidroid.xutils.bitmap.callback.BitmapLoadFrom;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;

import org.json.JSONException;
import org.json.JSONObject;

import malus.shaofeng.com.beiwomusic.R;
import malus.shaofeng.com.beiwomusic.model.LoginUser;
import malus.shaofeng.com.beiwomusic.utils.BitmapHelper;
import malus.shaofeng.com.beiwomusic.utils.SPHelper;
import malus.shaofeng.com.beiwomusic.utils.UserHelper;
import malus.shaofeng.com.beiwomusic.view.SildingFinishLayout;
import malus.shaofeng.com.beiwomusic.view.Topbar;

@ContentView(R.layout.activity_activity_user_message)
public class ActivityUserMessage extends Activity implements SildingFinishLayout.OnSildingFinishListener, Topbar.onTopbarClickListener, View.OnClickListener {
    @ViewInject(R.id.userMessageSildingFinishLayout)
    SildingFinishLayout sildingFinishLayout;
    @ViewInject(R.id.topbar)
    Topbar topbar;
    //点击换头像
    @ViewInject(R.id.activity_user_message_icon)
    LinearLayout mIcon;
    //点击换昵称
    @ViewInject(R.id.activity_user_message_nickname)
    LinearLayout mNickname;
    //点击换城市
    @ViewInject(R.id.activity_user_message_city)
    LinearLayout mCity;
    //点击换性别
    @ViewInject(R.id.activity_user_message_sex)
    LinearLayout mSex;
    //点击显示或隐藏下面选择框
    @ViewInject(R.id.activity_user_message_select_icon)
    LinearLayout bottomSelect;
    //点击下面选择框1
    @ViewInject(R.id.activity_user_message_check1)
    LinearLayout check1;
    //下面选择框2
    @ViewInject(R.id.activity_user_message_check2)
    LinearLayout check2;
    //取消下面选择框
    @ViewInject(R.id.activity_user_message_check_cansol)
    LinearLayout cansol;
    @ViewInject(R.id.activity_user_message_text_1)
    TextView txtCheck1;
    @ViewInject(R.id.activity_user_message_text_2)
    TextView txtCheck2;
    //填写昵称
    Dialog dialog;
    @ViewInject(R.id.activity_user_message_item_icon)
    ImageView mItemIcon;
    @ViewInject(R.id.activity_user_message_item_nickname)
    TextView mItemNickname;
    @ViewInject(R.id.activity_user_message_item_sex)
    TextView mItemSex;
    @ViewInject(R.id.activity_user_message_item_location)
    TextView mItemLocation;
    private LoginUser user;

    EditText dialogNickname;
    Button dialogCancel;
    Button dialogYes;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        ViewUtils.inject(this);
        sildingFinishLayout.setOnSildingFinishListener(this);
        topbar.setOnTopbarClickListener(this);
        setSettingSelector();
        //添加dialog
        dialog=new Dialog(this);
        View dialogView = LayoutInflater.from(this).inflate(R.layout.item_activity_user_message_dialog,null);
        dialogNickname=(EditText)dialogView.findViewById(R.id.dialog_modify_btn_nickname);
        dialogCancel=(Button)dialogView.findViewById(R.id.dialog_modify_btn_cancel);
        dialogYes=(Button)dialogView.findViewById(R.id.dialog_modify_btn_yes);
        dialog.setContentView(dialogView);
        dialog.getWindow().setBackgroundDrawable(getResources().getDrawable(R.drawable.transaction));
        dialogCancel.setOnClickListener(this);
        dialogYes.setOnClickListener(this);


        initData();
    }

    /**
     * 初始化信息
     */
    private void initData(){
        UserHelper userHelper = UserHelper.getInstance();
        user = userHelper.getUser();
        if(user==null){
            return;
        }

        if(!TextUtils.isEmpty(user.getNickname())) {
            mItemNickname.setText(user.getNickname());
        }
        if(user.getSex()==2) {
            mItemSex.setText("男");
        }else{
            mItemSex.setText("女");
        }
        String location="";
            if(!TextUtils.isEmpty(user.getProvince())) {
                location+= user.getProvince();
        }
            if(!TextUtils.isEmpty(user.getCity())) {
                location+= user.getCity();
        }
        mItemLocation.setText(location);
            if(!TextUtils.isEmpty(user.getFace_uri())){
            BitmapUtils bitmapUtils = BitmapHelper.getBitmapUtils();
            String face_uri = user.getFace_uri();
            String imageUrl = BitmapHelper.getImageUrl(face_uri);
            bitmapUtils.display(mItemIcon, imageUrl, new BitmapLoadCallBack<ImageView>() {
                @Override
                public void onLoadCompleted(ImageView imageView, String s, Bitmap bitmap, BitmapDisplayConfig bitmapDisplayConfig, BitmapLoadFrom bitmapLoadFrom) {
                    int width = bitmap.getWidth();
                    Bitmap dst = Bitmap.createBitmap(width, width, Bitmap.Config.ARGB_8888);
                    Paint paint = new Paint();
                    paint.setShader(new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
                    Canvas canvas = new Canvas(dst);
                    canvas.drawCircle(width / 2, width / 2, width / 2, paint);
                    imageView.setImageBitmap(dst);
                }

                @Override
                public void onLoadFailed(ImageView imageView, String s, Drawable drawable) {

                }
            });
        }
    }


    /**
     * 设置头像、昵称、城市、性别点击事件
     */
    private void setSettingSelector() {
        mIcon.setOnClickListener(this);
        mNickname.setOnClickListener(this);
        mCity.setOnClickListener(this);
        mSex.setOnClickListener(this);
        check1.setOnClickListener(this);
        check2.setOnClickListener(this);
        cansol.setOnClickListener(this);
    }

    @Override
    public void onSildingFinish() {
        finish();
        overridePendingTransition(0,R.anim.trans_slider_out);

    }

    @Override
    public void onBackPressed() {
        finish();
        overridePendingTransition(0,R.anim.trans_slider_out);

    }

    @Override
    public void onLeftButtonClick() {
        finish();
        overridePendingTransition(0,R.anim.trans_slider_out);

    }

    @Override
    public void onRightButtonClick() {

    }

    @Override
    public void onSearchButtonClick() {
    }

    /**
     * 更改个人信息
     */
    public void modifyUser(){
        //http://kxai.cn/qms/ws/user/modifyUser.json?
        // token=a95b2d3b8d4f082956ce579f4016661e&
        // nickname=%E8%BF%99%E5%90%8D%E5%AD%97%E7%9C%9F33&
        // sex=1&
        // faceuri=%2Fmnt%2Fres.nmting.com%2Fres%2Fqms%2Ficon%2F29.jpg&
        // province=&
        // city=
        //修改信息

        HttpUtils httpUtils=new HttpUtils();
        RequestParams params = new RequestParams();
        params.addBodyParameter("token", SPHelper.getInstance().getToken());
        params.addBodyParameter("nickname",user.getNickname());
        params.addBodyParameter("sex",user.getSex()+"");
        params.addBodyParameter("faceuri",user.getFace_uri());
        params.addBodyParameter("province",user.getProvince());
        params.addBodyParameter("city",user.getCity());
        httpUtils.send(
                HttpRequest.HttpMethod.POST,
                "http://kxai.cn/qms/ws/user/modifyUser.json",
                params,
                new RequestCallBack<Object>() {
            @Override
            public void onSuccess(ResponseInfo<Object> objectResponseInfo) {
                String result = objectResponseInfo.result.toString();
                try {
                    JSONObject object=new JSONObject(result);
                    JSONObject response = object.getJSONObject("response");
                    JSONObject userJSON = response.getJSONObject("user");
                    user.parseJSON(userJSON);
                    UserHelper userHelper=UserHelper.getInstance();
                    userHelper.setUser(user);
                    //修改后刷新界面
                    initData();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Toast.makeText(ActivityUserMessage.this,"修改错误",Toast.LENGTH_SHORT).show();
            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.activity_user_message_icon:
                txtCheck1.setText("从相册中选择");
                txtCheck2.setText("相册拍照");
                bottomSelect.setVisibility(View.VISIBLE);
                break;
            case R.id.activity_user_message_nickname:
                bottomSelect.setVisibility(View.INVISIBLE);
                dialog.show();
                break;
            case R.id.activity_user_message_city:
                bottomSelect.setVisibility(View.INVISIBLE);
                break;
            case R.id.activity_user_message_sex:
                txtCheck1.setText("男");
                txtCheck2.setText("女");
                bottomSelect.setVisibility(View.VISIBLE);
                break;
            case R.id.activity_user_message_check1:
                bottomSelect.setVisibility(View.INVISIBLE);
                String s1 = txtCheck1.getText().toString();
                //如果修改的是性别
                if(s1.equals("男")){
                    user.setSex(2);
                }else{
                    //修改的是头像
                }
                modifyUser();
                break;
            case R.id.activity_user_message_check2:
                bottomSelect.setVisibility(View.GONE);
                String s2 = txtCheck2.getText().toString();
                //如果修改的是性别
                if(s2.equals("女")){
                    user.setSex(1);
                }else{
                    //修改的是头像
                }
                modifyUser();
                break;
            case R.id.activity_user_message_check_cansol:
                bottomSelect.setVisibility(View.GONE);
                break;
            case R.id.dialog_modify_btn_cancel:
                if(dialog!=null){
                    dialog.cancel();
                }
                break;
            case R.id.dialog_modify_btn_yes:
                if(dialog!=null){
                    String newName = dialogNickname.getText().toString();
                    if(!TextUtils.isEmpty(newName)){
                        user.setNickname(newName);
                        modifyUser();
                    }
                    dialog.cancel();
                }
                break;

        }
    }
}
